package com.pmcc.cj.service;

import com.pmcc.cj.entity.*;
import com.pmcc.cj.entity.vo.OrderDetailVo;
import com.pmcc.cj.entity.vo.OrderVo;
import com.pmcc.cj.repository.*;
import com.pmcc.cj.vo.OrderCarVo;
import com.pmcc.cj.vo.QrRobotDetailVo;
import com.pmcc.cj.vo.QrRobotVo;
import com.pmcc.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by tomas on 2020/10/5.
 */
@Transactional
@Service
public class CjOrderService {
    @Autowired
    CjOrderRepository cjOrderRepository;
    @Autowired
    @Qualifier("primaryJdbcTemplate")
    private JdbcTemplate jdbcTemplate;
    @Autowired
    CjMoneyRecordRepository cjMoneyRecordRepository;
    @Autowired
    CjCustomerRepository cjCustomerRepository;
    @Autowired
    CjTaskRepository cjTaskRepository;
    @Autowired
    CjOrderDetailRepository cjOrderDetailRepository;
    @Autowired
    CjOrderIndexRepository cjOrderIndexRepository;
    @Autowired
    CjWechatService cjWechatService;


    public ResultBean queryOrderSpecialByPage(CjOrderIndex model, AntdPage antdPage){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            List<CjOrderIndex> list = new ArrayList<>();
            CjOrder order1 = new CjOrder();
            order1.setPayStatus(model.getPayStatus());
            order1.setEmployeeId(OnlineUser.getEmployeeId());
            order1.setFlags(model.getFlags());
            Page page=cjOrderRepository.findAll(this.getSpecification(order1),antdPage.getPageRequest());
            if(page != null && page.getContent().size()>0){
                for(CjOrder order:(List<CjOrder>) page.getContent()){
                    CjOrderIndex cjOrderIndex = new CjOrderIndex();
                    cjOrderIndex.setId(order.getOrderIndexId());
                    List<OrderVo> lt=new ArrayList<>();
                    OrderVo orderVo = new OrderVo();
                    orderVo.setId(order.getId());
                    orderVo.setGenre(order.getGenre()+"");
                    orderVo.setTotalmoney(order.getMoney().toString());
                    orderVo.setIsSaleRule(order.getIsSaleRule()+"");
                    orderVo.setIsNormal(order.getIsNormal()+"");
                    orderVo.setYunNum(order.getCommodityCount()+"");
                    orderVo.setYun(order.getYunId());
                    orderVo.setShopName(order.getYunName());
                    orderVo.setYunPrice(order.getPrice().toString());
                    orderVo.setPayStatus(order.getPayStatus());
                    String sql="select * from cj_commodity_yun where id = '" + order.getYunId() +"'";
                    List<CjCommodityYun> yun=jdbcTemplate.query(sql,new BeanPropertyRowMapper(CjCommodityYun.class));
                    orderVo.setImageUrl(yun.get(0).getAddress());
                    sql ="select * from cj_order_detail where order_id='" + order.getId() +"'";
                    List<CjOrderDetail> lt1=jdbcTemplate.query(sql,new BeanPropertyRowMapper(CjOrderDetail.class));
                    List<OrderDetailVo> lt2=new ArrayList<>();
                    if(lt1 != null && lt1.size()>0){
                        for(CjOrderDetail orderDetail: lt1){
                            OrderDetailVo orderDetailVo = new OrderDetailVo();
                            orderDetailVo.setId(orderDetail.getId());
                            orderDetailVo.setDose(orderDetail.getNumber()+"");
                            orderDetailVo.setName(orderDetail.getName());
                            lt2.add(orderDetailVo);
                        }
                    }
                    orderVo.setOrderDetailVos(lt2);
                    lt.add(orderVo);
                    cjOrderIndex.setOrderVos(lt);
                    list.add(cjOrderIndex);
                }
            }
            resultBean.setPage(antdPage.getDefaultCurrent());
            resultBean.setTotal(page.getTotalElements());
            resultBean.setPageSize(antdPage.getPageSize());
            resultBean.setRows(list);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public Specification<CjOrder> getSpecification(CjOrder model) {
        return new Specification<CjOrder>() {
            @Override
            public Predicate toPredicate(Root<CjOrder> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                List<Predicate> list = new ArrayList<Predicate>();
                if(model.getPayStatus()!= null){
                    list.add(builder.equal(root.get("payStatus").as(Integer.class),  model.getPayStatus()));
                }
                if(StringUtil.isNotEmpty(model.getEmployeeId())){
                    list.add(builder.equal(root.get("employeeId").as(String.class),  model.getEmployeeId()));
                }else {
                    //如果没传则查询当前登录人的
                    list.add(builder.equal(root.get("employeeId").as(String.class), OnlineUser.getEmployeeId()));
                }
                if(model.getFlags() != null){
                    int[] num = {2,6,7};
                    CriteriaBuilder.In in = builder.in((root.get("payStatus").as(Integer.class)));
                    for (int a : num) {
                        in.value(a);
                    }
                    list.add(in);
                }
                query.orderBy(builder.desc(root.get("createTime").as(Date.class)));
                Predicate[] p = new Predicate[list.size()];
                return builder.and(list.toArray(p));
            }
        };
    }
    public ResultBean refundOrder(String id){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjOrder order = cjOrderRepository.findOne(id);
            order.setPayStatus(6);
            cjOrderRepository.saveAndFlush(order);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean confirmRefund(String id){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjOrder order = cjOrderRepository.findOne(id);
            order.setPayStatus(2);
            cjOrderRepository.saveAndFlush(order);
            //金额变动
            CjMoneyRecord moneyRecord1 = new CjMoneyRecord();
            moneyRecord1.setMoney(order.getMoney());
            moneyRecord1.setOrderId(id);
            moneyRecord1.setCustomerIncomeId(order.getEmployeeId());
            moneyRecord1.setCustomerPayId("2c978b23752a450d01752aff74c8954g");
            moneyRecord1.setCreateDate(new Date());
            moneyRecord1.setFettle(2);
            moneyRecord1.setCustomerBelongId("2c978b23752a450d01752aff74c8954g");
            moneyRecord1.setName("平台");
            cjMoneyRecordRepository.saveAndFlush(moneyRecord1);
            CjCustomer customer1 = cjCustomerRepository.findOne("2c978b23752a450d01752aff74c8954g");
            customer1.setMoney(customer1.getMoney().subtract(order.getMoney()));
            cjCustomerRepository.saveAndFlush(customer1);

            CjCustomer customer2 = cjCustomerRepository.findOne(order.getEmployeeId());
            CjMoneyRecord moneyRecord2 = new CjMoneyRecord();
            moneyRecord2.setMoney(order.getMoney());
            moneyRecord2.setOrderId(id);
            moneyRecord2.setCustomerIncomeId(order.getEmployeeId());
            moneyRecord2.setCustomerPayId("2c978b23752a450d01752aff74c8954g");
            moneyRecord2.setCreateDate(new Date());
            moneyRecord2.setFettle(1);
            moneyRecord2.setCustomerBelongId(order.getEmployeeId());
            moneyRecord2.setName(customer2.getCardName());
            cjMoneyRecordRepository.saveAndFlush(moneyRecord2);
            customer2.setMoney(customer2.getMoney().add(order.getMoney()));
            cjCustomerRepository.saveAndFlush(customer2);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    public ResultBean confirmRefundRefuse(String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjOrder order = cjOrderRepository.findOne(id);
            order.setPayStatus(7);
            cjOrderRepository.saveAndFlush(order);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.SUCCESS);
        }
        return resultBean;
    }

        public ResultBean queryOrderIndexWebByPage(CjOrder model, AntdPage antdPage){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            List<OrderVo> lt = new ArrayList<>();
            Page page=cjOrderRepository.findAll(this.getSpecificationWeb(model),antdPage.getPageRequest());
            if(page != null && page.getContent().size()>0){
                for (CjOrder order : (List<CjOrder>) page.getContent()){
                    OrderVo orderVo =new OrderVo();
                    orderVo.setOrderIndexId(order.getOrderIndexId());
                    orderVo.setId(order.getId());
                    orderVo.setGenre(order.getGenre()+"");
                    orderVo.setTotalmoney(order.getMoney().toString());
                    orderVo.setIsSaleRule(order.getIsSaleRule()+"");
                    orderVo.setIsNormal(order.getIsNormal()+"");
                    orderVo.setYunNum(order.getCommodityCount()+"");
                    orderVo.setYun(order.getYunId());
                    orderVo.setShopName(order.getYunName());
                    orderVo.setYunPrice(order.getPrice().toString());
                    orderVo.setPayStatus(order.getPayStatus());
                    String sql="select * from cj_commodity_yun where id = '" + order.getYunId() +"'";
                    List<CjCommodityYun> yun=jdbcTemplate.query(sql,new BeanPropertyRowMapper(CjCommodityYun.class));
                    orderVo.setImageUrl(yun.get(0).getAddress());
                    sql ="select * from cj_order_detail where order_id='" + order.getId() +"'";
                    List<CjOrderDetail> lt1=jdbcTemplate.query(sql,new BeanPropertyRowMapper(CjOrderDetail.class));
                    List<OrderDetailVo> lt2=new ArrayList<>();
                    if(lt1 != null && lt1.size()>0){
                        for(CjOrderDetail orderDetail: lt1){
                            OrderDetailVo orderDetailVo = new OrderDetailVo();
                            orderDetailVo.setId(orderDetail.getId());
                            orderDetailVo.setDose(orderDetail.getNumber()+"");
                            orderDetailVo.setName(orderDetail.getName());
                            lt2.add(orderDetailVo);
                        }
                    }
                    orderVo.setOrderDetailVos(lt2);
                    lt.add(orderVo);
                }
            }
            resultBean.setPage(antdPage.getDefaultCurrent());
            resultBean.setTotal(page.getTotalElements());
            resultBean.setPageSize(antdPage.getPageSize());
            resultBean.setRows(lt);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public Specification<CjOrder> getSpecificationWeb(CjOrder model) {
        return new Specification<CjOrder>() {
            @Override
            public Predicate toPredicate(Root<CjOrder> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                List<Predicate> list = new ArrayList<Predicate>();
                if(model.getPayStatus()!= null){
                    if(model.getPayStatus() ==2){
                        int[] num = {2,7};
                        CriteriaBuilder.In in = builder.in((root.get("payStatus").as(Integer.class)));
                        for (int a : num) {
                            in.value(a);
                        }
                        list.add(in);
                    }else{
                        list.add(builder.equal(root.get("payStatus").as(Integer.class),  model.getPayStatus()));
                    }
                }
                if(StringUtil.isNotEmpty(model.getOrderIndexId())){
                    list.add(builder.like(root.get("orderIndexId").as(String.class),  "%"+model.getOrderIndexId().trim()+"%"));
                }
                if(model.getSearches() != null && model.getSearches().length>1){
                    list.add(builder.between(root.get("createTime").as(Date.class), DateUtil.StringToDate(model.getSearches()[0],DateUtil.YYYY_MM_DD_HH_MM_SS), DateUtil.StringToDate(model.getSearches()[1],DateUtil.YYYY_MM_DD_HH_MM_SS)));
                }
                query.orderBy(builder.desc(root.get("createTime").as(Date.class)));
                Predicate[] p = new Predicate[list.size()];
                return builder.and(list.toArray(p));
            }
        };
    }

    public ResultBean qrData(String id){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjCustomer cjCustomer = cjCustomerRepository.findOne(id);
            QrRobotVo qrRobotVo = new QrRobotVo();
            qrRobotVo.setName(cjCustomer.getCardName());
            qrRobotVo.setCellphone(cjCustomer.getCellphone());
            List<QrRobotDetailVo> list = new ArrayList<>();
            List<CjTask> lt=cjTaskRepository.findByRobotIdAndFettleTaskAndFettleTypeAndRobotFlag(id,0,1,"0");
            if(lt != null && lt.size()>0){
                for(CjTask task:lt){
                    QrRobotDetailVo qrRobotDetailVo = new QrRobotDetailVo();
                    qrRobotDetailVo.setBeginTime(task.getBeginTime());
                    qrRobotDetailVo.setYunName(task.getYunName());
                    qrRobotDetailVo.setYunNum(task.getNumber().toString());
                    qrRobotDetailVo.setTaskId(task.getId());
                    qrRobotDetailVo.setRobotFettle(task.getRobotFlag());
                    List<OrderDetailVo> list1 = new ArrayList<>();
                    if(StringUtil.isNotEmpty(task.getRobotTaskId())){
                        //特质订单
                        qrRobotDetailVo.setOrderIndexId(task.getRobotTaskId());
                    }else {
                        //云飞防订单
                        CjOrder order = cjOrderRepository.findOne(task.getOrderId());
                        qrRobotDetailVo.setOrderIndexId(order.getOrderIndexId());
                        List<CjOrderDetail> lt1 = cjOrderDetailRepository.findByOrderId(order.getId());
                        if(lt1 != null && lt1.size()>0){
                            for(CjOrderDetail orderDetail: lt1){
                                OrderDetailVo orderDetailVo = new OrderDetailVo();
                                orderDetailVo.setName(orderDetail.getName());
                                orderDetailVo.setDose(orderDetail.getNumber().toString());
                                list1.add(orderDetailVo);
                            }
                        }
                    }
                    qrRobotDetailVo.setDetailVos(list1);
                    list.add(qrRobotDetailVo);
                }
            }
            qrRobotVo.setDetailVos(list);
            resultBean.setObject(qrRobotVo);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean robotTask(String id){
        ResultBean resultBean =new ResultBean(ResultBean.SUCCESS);
        try {
            CjTask task =cjTaskRepository.findOne(id);
            task.setRobotFlag("1");
            cjTaskRepository.saveAndFlush(task);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean orderIndexConfirm(String orderIndexId){
        ResultBean resultBean = new ResultBean(ResultBean.FAIL);
        try {
            CjOrderIndex orderIndex=cjOrderIndexRepository.findOne(orderIndexId);
            if(orderIndex != null){
                if(orderIndex.getPayStatus() ==0){
                    Map<String, String> map= cjWechatService.orderQuery(orderIndex.getPayId(),orderIndexId);
                    if(map != null && map.size()>0){
                        if(ResultBean.SUCCESS.equals(map.get("resultCode"))){
                            resultBean.setResultCode(ResultBean.SUCCESS);
                        }
                    }
                }else {
                    resultBean.setResultDesc("改订单已处理，无需重复操作");
                }
            }else {
                resultBean.setResultDesc("无此订单");
            }
        }catch (Exception e){
        }
        return resultBean;
    }
}
